import { menuTypeEnum } from "@/enums/menu"
import useHomeStore from "@/stores/home"
import type { RouteRecordRaw } from "vue-router"

/**
 * 加载本地路由文件
 */
const loadLocalRoutes = () => {
  const localRoutes: RouteRecordRaw[] = []

  // 获取router下的所有ts文件 动态注册路由需要在router文件夹下先写好路由文件
  // eager: true  直接引入所有的模块
  const files: Record<string, any> = import.meta.glob("../routes/**/*.ts", { eager: true })

  // 将加载的对象放在 localRoutes 里
  for (const key in files) {
    const module = files[key]
    localRoutes.push(module.default)
  }

  return localRoutes
}

/**
 * 根据菜单获取相应的路由信息
 *
 * @param menuList 首页菜单列表
 */
const mapMenusToRoutes = (menuList: MenuTreeResponse[]) => {
  const localRoutes = loadLocalRoutes()

  const routes: RouteRecordRaw[] = []

  function _recurseGetRoute(menus: MenuTreeResponse[] = []) {
    for (const menu of menus) {
      if (menu.menuType === menuTypeEnum.MENU) {
        const route = localRoutes.find((item) => item.path === menu.path)
        if (route) {
          routes.push(route)
        }
      } else if (menu.children && menu.children.length > 0) {
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(menuList)

  return routes
}

/**
 * 根据路径映射菜单
 *
 * @param menus 菜单列表
 * @param path 当前路径
 */
const mapPathToMenu = (menus: MenuTreeResponse[], path: string): MenuTreeResponse | null => {
  for (const menu of menus) {
    if (menu.menuType === menuTypeEnum.DIRECTORY && menu.children && menu.children.length > 0) {
      // 如果是目录，递归遍历子菜单
      const findMenu = mapPathToMenu(menu.children, path)
      if (findMenu) {
        return findMenu
      }
    } else if (menu.path === path && menu.menuType !== menuTypeEnum.BUTTON) {
      return menu
    }
  }

  return null
}

/**
 * 获取进入后的首个页面
 *
 * @param menus 菜单列表
 */
const getFirstMenu = (menus: MenuTreeResponse[]): MenuTreeResponse | null => {
  for (const menu of menus) {
    if (menu.menuType === menuTypeEnum.DIRECTORY && menu.children && menu.children.length > 0) {
      // 如果是目录，递归遍历子菜单
      const findMenu = getFirstMenu(menu.children)
      if (findMenu) {
        return findMenu
      }
    } else if (menu.menuType !== menuTypeEnum.BUTTON) {
      return menu
    }
  }

  return null
}

/**
 * 增加菜单标签 Tab
 *
 * @param menuTab 菜单标签
 */
const addMenuTab = (menuTab: MenuTab) => {
  if (!menuTab) return
  const homeStore = useHomeStore()
  const menuTabs = homeStore.menuTabs
  const tab = menuTabs.find((tab) => tab.path === menuTab.path)
  if (!tab) {
    homeStore.addMenuTabAction(menuTab)
  }
}

export { loadLocalRoutes, mapMenusToRoutes, mapPathToMenu, getFirstMenu, addMenuTab }
